package com.typing.service.impl;

import com.typing.entity.UserEntity;
import com.typing.mapper.UserMapper;
import com.typing.service.UserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	UserMapper userMapper;


	@Override
	public int addUser(UserEntity user) {
		//	通过对UUID进行MD5加密生成盐，再将密码进行3次MD5加盐的加密储存
		String salt = DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes());
		SimpleHash simpleHash = new SimpleHash("MD5", user.getPassword(), salt, 3);
		String newPassword = simpleHash.toHex();
		user.setPassword(newPassword);
		user.setSalt(salt);
		return userMapper.addUser(user);
	}

	@Override
	public int updatePassword(UserEntity user) {
		String salt = DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes());
		SimpleHash simpleHash = new SimpleHash("MD5", user.getPassword(), salt, 3);
		String newPassword = simpleHash.toHex();
		user.setPassword(newPassword);
		user.setSalt(salt);
		return userMapper.resetPassword(user);
	}

	@Override
	public UserEntity userLogin(UserEntity user) {
		String salt = userMapper.getSalt(user.getMobilePhone());
		SimpleHash simpleHash = new SimpleHash("MD5", user.getPassword(), salt, 3);
		String newPassword = simpleHash.toHex();
		user.setPassword(newPassword);
		return userMapper.selectUser(user);
	}

	@Override
	public UserEntity getNewUser(UserEntity user) {
		return userMapper.selectUser(user);
	}

	@Override
	public int setTag(UserEntity user) {
		return userMapper.setTag(user);
	}

	@Override
	public UserEntity selectTag(String tag) {
		return userMapper.selectTag(tag);
	}

	@Override
	public UserEntity isRegister(UserEntity user) {
		return userMapper.isRegister(user);
	}


	@Override
	public List<UserEntity> selectRankingTeacher() {
		return userMapper.selectRankingTeacher();
	}

	@Override
	public List<UserEntity> selectRankingStudent() {
		return userMapper.selectRankingStudent();
	}

	@Override
	public int setScore(UserEntity user) {
		return userMapper.setScore(user);
	}

	@Override
	public List<UserEntity> selectAllUser() {
		return userMapper.selectAllUser();
	}

	@Override
	public UserEntity selectUserById(Integer id) {
		return userMapper.selectUserById(id);
	}
}
